<template>
  <el-drawer
    v-model="visible"
    :close-on-click-modal="true"
    size="50%"
    :destroy-on-close="true"
    direction="rtl"
    class="document-drawer"
  >
    <template #header>
      <div class="flex gap-3 items-center py-1">
        <h2 class="max-w-md text-lg font-semibold text-gray-800 truncate">{{ documentTitle }}</h2>
      </div>
    </template>
    
    <div class="px-4 py-2 h-full">
      <!-- 选项卡 -->
      <el-tabs v-model="activeTab" class="h-full flex flex-col">
        <!-- 文档展示选项卡 -->
        <el-tab-pane label="文档展示" name="document" class="flex-1">
          <div class="h-full">
            <el-scrollbar height="calc(100vh - 180px)" ref="scrollbarRef" @scroll="onScroll">
              <div class="document-content">
                <div
                  v-for="(slice, index) in slices"
                  :key="slice.id"
                  class="slice-section relative"
                  :class="{ 'slice-highlight': selectedSliceId === slice.id }"
                  @click="selectSlice(slice)"
                  @dblclick="startEditing(slice)"
                  :id="`slice-${slice.id}`"
                >
                  <!-- Slice info - only shown when selected, positioned at top-right -->
                  <div 
                    v-if="selectedSliceId === slice.id" 
                    class="slice-info absolute top-2 right-2 z-10 bg-white dark:bg-gray-800 rounded-md shadow-sm px-4 py-3 border border-gray-200"
                  >
                    <div class="flex items-center gap-4 text-sm">
                      <span v-if="selectedSlice?.sliceStatus === '1'" class="px-2 py-1 bg-primary text-white text-xs font-bold rounded">
                        已训练
                      </span>
                      <div class="flex items-center">
                        <svg
                          class="w-4 h-4 mr-1 text-gray-500"
                          viewBox="0 0 1024 1024"
                          version="1.1"
                          xmlns="http://www.w3.org/2000/svg"
                        >
                          <path
                            d="M639.2 282.6l80.2-80.6c5.9-5.6 15.3-5.6 20.7 0 2.3 2.3 3.3 4.3 4 6.6V209.2l15 55.7 55.7 15 0.3 0.2h0.2c2.3 0.7 4.7 1.6 6.4 3.8 5.7 5.6 5.7 14.8 0 20.7l-80 80.2c-3.8 3.7-9 5.2-14.4 3.8l-45.1-12-23 23.3c25.1 32 39.8 72.9 39.8 117.2 0 52.5-21.4 100.7-56.2 135.5l-0.7 0.5c-35 34.8-82.4 56-135 56-52.9 0-101.1-21.6-135.7-56.5-34.8-34.8-56.4-83-56.4-135.5 0-53.1 21.6-100.9 56.4-135.9C406 346.4 454.2 325 507.1 325c44.2 0 84.9 14.8 117.3 39.8l23.1-22.8-12.2-45.4c-1.5-4.9 0.2-10.5 3.9-14z"
                            fill="currentColor"
                          ></path>
                        </svg>
                        <span>命中: {{ selectedSlice?.hitCount || 0 }}</span>
                      </div>
                      <div class="flex items-center">
                        <svg
                          class="mr-1 w-5 h-5"
                          viewBox="0 0 1024 1024"
                          version="1.1"
                          xmlns="http://www.w3.org/2000/svg"
                        >
                          <path
                            d="M109.568 99.328s-17.408 15.36 0 38.912 295.936 392.192 295.936 392.192 17.408 15.36 0 35.84-288.768 323.584-288.768 323.584-20.48 32.768 3.072 32.768h733.184s27.648 0 33.792-29.696c7.168-29.696 33.792-154.624 33.792-154.624s0-12.288-10.24-17.408c-10.24-6.144-30.72 0-33.792 9.216-3.072 9.216-92.16 98.304-125.952 104.448h-471.04l237.568-273.408s17.408-12.288 17.408-29.696-23.552-45.056-23.552-45.056L276.48 169.984h458.752s88.064 47.104 146.432 136.192c7.168 9.216 40.96 9.216 40.96 0s-51.2-201.728-51.2-201.728l-761.856-5.12z"
                            fill="currentColor"
                          ></path>
                        </svg>
                        <span>字符: {{ selectedSlice?.charCount || 0 }}</span>
                      </div>
                    </div>
                    
                    <div class="flex mt-3 gap-3">
                      <el-button size="small" class="flex items-center" type="primary" @click="startEditing(slice)" text>
                        <el-icon class="mr-1"><Edit /></el-icon>编辑
                      </el-button>
                      <el-button size="small" class="flex items-center" type="warning" @click="handleRetrain(slice)" text v-if="slice.sliceStatus === '1'">
                        <el-icon class="mr-1"><Refresh /></el-icon>重新训练
                      </el-button>
                    </div>
                  </div>
                  
                  <!-- 显示内容或编辑框 -->
                  <div v-if="!editingSlice || editingSlice.id !== slice.id">
                    <MdRenderer :source="slice.content" :key="`md-${slice.id}`" />
                  </div>
                  <el-input
                    v-else
                    type="textarea"
                    v-model="editingContent"
                    :autosize="{ minRows: 6, maxRows: 10 }"
                    @blur="saveContent(slice)"
                    ref="editInputRef"
                    class="slice-editor"
                  />
                </div>
                
                <div v-if="slices.length === 0" class="text-center py-10 text-gray-500">
                  当前文档暂无切片内容
                </div>
                
                <div v-if="loading" class="text-center py-4">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  <span class="ml-2">加载中...</span>
                </div>
                
                <div v-if="noMoreData && slices.length > 0" class="text-center py-4 text-gray-400 text-sm">
                  没有更多数据了
                </div>
                
                <!-- Add a loading trigger element at the bottom -->
                <div v-if="!noMoreData && !loading" class="loading-trigger h-10" ref="loadTriggerRef"></div>
              </div>
            </el-scrollbar>
          </div>
        </el-tab-pane>
        
        <!-- 文档关键词选项卡 -->
        <el-tab-pane label="文档关键词" name="keywords" class="flex-1">
          <div class="h-full flex items-center justify-center">
            <div v-if="!props.documentId" class="text-center text-gray-500">
              <el-icon class="text-2xl mb-2"><Picture /></el-icon>
              <div>请选择文档</div>
            </div>
            <div v-else class="w-full h-full flex items-center justify-center">
              <img 
                :src="`${baseURL}${other.adaptationUrl('/knowledge/aiDocument/wordcloud')}?documentId=${props.documentId}`" 
                alt="关键词云图" 
                class="max-w-full max-h-full object-contain"
                style="max-height: calc(100vh - 200px);"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { getObj as getDocument } from '/@/api/knowledge/aiDocument';
import { useMessage, useMessageBox } from '/@/hooks/message';
import MdRenderer from '/@/components/MdRenderer/MdRenderer.vue';
import { Loading, Edit, Refresh, Picture } from '@element-plus/icons-vue';
import { putObj,fetchList } from '/@/api/knowledge/aiSlice';
import { useIntersectionObserver } from '@vueuse/core';
import other from '/@/utils/other';

const props = defineProps({
  documentId: {
    type: String,
    default: ''
  },
  sliceId: {
    type: String,
    default: ''
  },
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue']);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

const documentTitle = ref('文档查看');
const slices = ref<any[]>([]);
const selectedSliceId = ref<string | null>(null);
const selectedSlice = ref<any>(null);
const scrollbarRef = ref<any>(null);
const loading = ref(false);
const noMoreData = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);
const totalSlices = ref(0);
const allSlicesLoaded = ref(false);
// 编辑相关变量
const editingSlice = ref<any>(null);
const editingContent = ref('');
const editInputRef = ref<HTMLElement | null>(null);
const loadTriggerRef = ref<HTMLElement | null>(null);

// 选项卡和关键词云图相关状态
const activeTab = ref('document');
const imageError = ref('');

// 获取文档切片列表
const getDocumentSlices = async (page = 1, append = false) => {
  if (!props.documentId || loading.value) return;
  
  try {
    loading.value = true;
    
    // 获取文档信息（仅在第一页时获取）
    if (page === 1) {
      const documentRes = await getDocument(props.documentId);
      if (documentRes && documentRes.data) {
        documentTitle.value = documentRes.data.name || '未命名文档';
      }
    }
    
    // 获取该文档的切片（分页）
    const { data } = await fetchList({
      documentId: props.documentId,
      current: page,
      size: pageSize.value,
    });
    
    if (data) {
      totalSlices.value = data.total;
      
      // 处理切片数据
      const newSlices = data.records.sort((a: any, b: any) => {
        // 如果有顺序字段使用顺序字段，否则按ID排序
        return (a.orderNum || 0) - (b.orderNum || 0);
      });
      
      // 如果返回的记录为空，设置没有更多数据标志
      if (newSlices.length === 0) {
        noMoreData.value = true;
        return;
      }
      
      // 追加或替换数据
      if (append) {
        slices.value = [...slices.value, ...newSlices];
      } else {
        slices.value = newSlices;
      }
      
      // 检查是否还有更多数据
      noMoreData.value = slices.value.length >= totalSlices.value;
      allSlicesLoaded.value = slices.value.length >= totalSlices.value;
    }
  } catch (error: any) {
    useMessage().error(error.msg || '获取文档切片失败');
  } finally {
    loading.value = false;
  }
};

// 加载更多数据
const loadMoreSlices = () => {
  if (loading.value || noMoreData.value) return;
  
  currentPage.value++;
  getDocumentSlices(currentPage.value, true);
};

// 滚动事件处理
const onScroll = ({ scrollTop, scrollHeight, clientHeight }: { scrollTop: number, scrollHeight: number, clientHeight: number }) => {
  // 当滚动到底部附近时加载更多数据
  if (scrollHeight - scrollTop - clientHeight < 200 && !loading.value && !noMoreData.value) {
    loadMoreSlices();
  }
};

// 使用 useIntersectionObserver 监听加载触发器元素
const { stop: stopObserver } = useIntersectionObserver(
  loadTriggerRef,
  ([{ isIntersecting }]) => {
    if (isIntersecting && !loading.value && !noMoreData.value && visible.value && slices.value.length > 0) {
      loadMoreSlices();
    }
  },
  {
    threshold: 0.1
  }
);

// 组件卸载时停止观察
onBeforeUnmount(() => {
  stopObserver();
});

// 选择切片
const selectSlice = (slice: any) => {
  if (selectedSliceId.value === slice.id) {
    selectedSliceId.value = null;
    selectedSlice.value = null;
  } else {
    selectedSliceId.value = slice.id;
    selectedSlice.value = slice;
  }
};

// 开始编辑
const startEditing = (slice: any) => {
  editingSlice.value = slice;
  editingContent.value = slice.content;
  nextTick(() => {
    // Use setTimeout to ensure the DOM is updated
    setTimeout(() => {
      const textareaElement = document.querySelector('.slice-editor textarea');
      if (textareaElement) {
        (textareaElement as HTMLTextAreaElement).focus();
      }
    }, 0);
  });
};

// 保存编辑内容
const saveContent = async (slice: any) => {
  // 内容没有变动
  if (editingContent.value === slice.content) {
    editingSlice.value = null;
    return;
  }

  // 内容为空
  if (!editingContent.value.trim()) {
    useMessage().error('内容不能为空');
    editingContent.value = slice.content;
    editingSlice.value = null;
    return;
  }

  try {
    await putObj({
      ...slice,
      content: editingContent.value
    });
    useMessage().success('修改成功');
    
    // 更新本地数据
    const index = slices.value.findIndex(s => s.id === slice.id);
    if (index !== -1) {
      slices.value[index].content = editingContent.value;
    }
    
    // 如果是当前选中的切片，也更新选中的切片
    if (selectedSlice.value && selectedSlice.value.id === slice.id) {
      selectedSlice.value.content = editingContent.value;
    }
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    editingSlice.value = null;
  }
};

// 重新训练操作
const handleRetrain = async (slice: any) => {
  try {
    await useMessageBox().confirm('确认要重新训练该切片吗？');
  } catch {
    return;
  }

  try {
    await putObj({ ...slice, sliceStatus: '0' });
    useMessage().success('已提交重新训练');
    
    // 更新本地数据
    const index = slices.value.findIndex(s => s.id === slice.id);
    if (index !== -1) {
      slices.value[index].sliceStatus = '0';
    }
    
    // 如果是当前选中的切片，也更新选中的切片
    if (selectedSlice.value && selectedSlice.value.id === slice.id) {
      selectedSlice.value.sliceStatus = '0';
    }
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

// 滚动到指定切片的位置
const scrollToSlice = async (sliceId: string) => {
  // 如果没有找到切片，可能需要加载更多数据
  if (!slices.value.some(s => s.id === sliceId) && !allSlicesLoaded.value) {
    // 重置并加载所有数据
    currentPage.value = 1;
    loading.value = true;
    
    try {
      // 获取所有切片数据以确保能找到目标切片
      const { data } = await fetchList({
        documentId: props.documentId,
        size: 999, // 大数值以获取所有切片
      });
      
      if (data && data.records) {
        slices.value = data.records.sort((a: any, b: any) => {
          return (a.orderNum || 0) - (b.orderNum || 0);
        });
        allSlicesLoaded.value = true;
        noMoreData.value = true;
      }
    } catch (error: any) {
      useMessage().error(error.msg || '获取文档切片失败');
    } finally {
      loading.value = false;
    }
  }
  
  nextTick(() => {
    const element = document.getElementById(`slice-${sliceId}`);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  });
};

// 重置分页状态
const resetPagination = () => {
  currentPage.value = 1;
  noMoreData.value = false;
  allSlicesLoaded.value = false;
  slices.value = [];
};

// 监听 visible 变化
watch(() => visible.value, (newVal) => {
  if (newVal && props.documentId) {
    resetPagination();
    getDocumentSlices();
    
    if (props.sliceId) {
      selectedSliceId.value = props.sliceId;
      scrollToSlice(props.sliceId);
    }
  } else if (!newVal) {
    // 关闭抽屉时重置状态
    activeTab.value = 'document';
    imageError.value = '';
  }
});

watch(() => props.documentId, (newVal) => {
  if (newVal && visible.value) {
    resetPagination();
    getDocumentSlices();
    // 重置图片错误状态
    imageError.value = '';
  }
});

watch(() => props.sliceId, (newVal) => {
  if (newVal && visible.value) {
    selectedSliceId.value = newVal;
    scrollToSlice(newVal);
  }
});

// Watch slices to update selectedSlice when data is loaded
watch(() => slices.value, (newSlices) => {
  if (selectedSliceId.value && newSlices.length > 0) {
    const slice = newSlices.find(s => s.id === selectedSliceId.value);
    if (slice) {
      selectedSlice.value = slice;
    }
  }
});

</script>